package fm.dongman.modellib.local;

import android.app.Activity;
import android.content.Context;
import android.util.Log;

import org.jetbrains.annotations.NotNull;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import fm.dongman.animefm.contractlib.BaseDataSource;
import fm.dongman.animefm.contractlib.IModel;
import fm.dongman.animefm.contractlib.contract.LoginContract;
import fm.dongman.animefm.contractlib.contract.MyContract;
import fm.dongman.modellib.model.UserModel;

/**
 * 本地加载用户信息
 * Created by KUIGE on 2017/10/13.
 */

public class LoginLocalDataSource implements LoginContract.ILoginDataSource {

    private Context context;
    private static LoginLocalDataSource INSTANCE;
    private DataOperationHelper mOperationHelper;

    public static LoginLocalDataSource getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = new LoginLocalDataSource(context);
        }
        return INSTANCE;
    }

    private LoginLocalDataSource(Context context) {
        this.context = context;
        mOperationHelper = DataOperationHelper.getDataOperationHelper(context);
    }

    @Override
    public void login(@NotNull String userName, @NotNull String pwd, @NotNull LoadSourceCallback<? super IModel.IUserModel> callback) {

    }

    @Override
    public void getData(@NotNull LoadSourceCallback<? super IModel.IUserModel> callback) {
        UserModel model = (UserModel) mOperationHelper.downUser();
        if (model.getToken() != null) {
            callback.onDataLoaded(model);
        } else callback.onDataLoadFiled();
    }

    @Override
    public void saveData(IModel.IUserModel dataModel) {
        List<IModel.IUserModel> models = new ArrayList<>();
        models.add(dataModel);
        mOperationHelper.addUser(models);
    }

    @Override
    public void refreshData() {

    }

    @Override
    public void offLine() {

    }

    @Override
    public void loginSocial(@NotNull Activity activity, int type, @NotNull LoadSourceCallback<? super IModel.IUserModel> callback) {

    }

    public void saveToken(JSONObject object) {
        mOperationHelper.saveToken(object);
    }

    public void onRefresh() {
        //从数据库读取token
        DataOperationHelper.getDataOperationHelper(context).downUser();
    }
}
